<template>
  <el-dialog v-model="addOrEditVisible" title="菜单管理" :before-close="closeEditDialog" width="60%">
    <el-form
        ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="160px" class="demo-ruleForm"
        :size="formSize" status-icon>
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级单位" prop="parentId">
            <el-cascader v-model="ruleForm.parentId" :options="parentDepts" :props="parentDeptProps"
                         :show-all-levels="false" placeholder="请选择上级单位" @change="parentDeptChange" filterable
                         clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单位名称" prop="deptName">
            <el-input v-model="ruleForm.deptName"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单位别称" prop="deptAlias">
            <el-input v-model="ruleForm.deptAlias"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单位图标" prop="deptIcon">
            <form-up-load-image @uploadImageCallback="uploadImageCallback"
                                :imageUrl="ruleForm.deptIcon"></form-up-load-image>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="负责人" prop="principal">
            <el-input v-model="ruleForm.principal"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="负责人手机" prop="principalPhone">
            <el-input v-model="ruleForm.principalPhone"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-row>-->
      <!--        <el-col :span="24">-->
      <!--          <el-form-item label="单位简介" prop="deptIntro">-->
      <!--            <el-input v-model="ruleForm.deptIntro" type="textarea"/>-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->

      <el-row>
        <el-col :span="24">
          <el-form-item label="地址" prop="province">
            <el-col :span="8" style="padding-right: 20px;">
              <el-select v-model="ruleForm.province" class="m-2" placeholder="省"
                         @change="provinceChange">
                <el-option
                    v-for="(item,index) in address.province"
                    key="index"
                    :label="item.areaName"
                    :value=item.code> </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" style="padding-right: 20px;" v-if="ruleForm.province">
              <el-select v-model="ruleForm.city" class="m-2" placeholder="市"
                         @change="cityChange">
                <el-option
                    v-for="(item, index) in address.city"
                    key="index"
                    :label="item.areaName"
                    :value=item.code> </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" v-if="ruleForm.city">
              <el-select v-model="ruleForm.district" class="m-2" placeholder="街道">
                <el-option
                    v-for="(item,index) in address.district"
                    key="index"
                    :label="item.areaName"
                    :value=item.code> </el-option>
              </el-select>
            </el-col>
            <el-col :span="24" class="address-top">
              <el-input v-model="ruleForm.address"/>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="排序" prop="deptSort">
            <el-input-number v-model="ruleForm.deptSort" :min="1"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeEditDialog">关闭</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref, toRef} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage} from "element-plus";
import router from "@/router";
import {Dept} from "@/apis/model/system/DeptModel";
import {findAreaByParentCode} from "@/apis/http/system/AreaHttp";
import {Area} from "@/apis/model/system/AreaModel";
import {deptLoop, insertDept, updateDept} from "@/apis/http/system/DeptHttp";
import FormUpLoadImage from "@/components/form/FormUpLoadImage.vue";
import {File} from "@/apis/model/system/FileModel";

interface Prop {
  addOrEditVisible: boolean,
  ruleForm: Dept,
  addDataType: string
}

interface Address {
  province: Array<Area>,
  city: Array<Area>,
  district: Array<Area>,
  addressDetail: string
}

// 刷新list页面
const refushList = ref(false);

// 传递过来的参数
const props = defineProps<Prop>();

const emit = defineEmits(["closeEditDialog"]);

const parentDepts = ref([] as Array<Dept>)
const parentDeptProps = {
  expandTrigger: 'click',
  multiple: false,
  value: 'id',
  label: 'deptName',
  children: 'children',
  checkStrictly: true
}

const address = reactive({
  province: [],
  city: [],
  district: [],
  addressDetail: ''
} as Address)

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  deptName: [
    {required: true, message: '请输入单位名称！', trigger: 'blur'}
  ]
})

// 关闭按钮
const closeEditDialog = () => {
  // ruleFormRef.resetFields();
  emit("closeEditDialog", {
    addOrEditVisible: !props.addOrEditVisible,
    refushList: refushList.value
  })
}
/**
 * 获取数据
 * @param value json类型的数据
 */
const parentDeptChange = (value: any) => {
  if (value == null) {
    props.ruleForm.parentId = -1;
    return;
  }

  for (var i = 0; i < 10; i++) {
    if (value[i] == undefined) {
      props.ruleForm.parentId = value[i - 1]
      break;
    }
  }
}

/**
 * 上传图片回调
 */
const uploadImageCallback = (e: File) => {
  props.ruleForm.deptIcon = e.url;
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 新增
      if (props.addDataType === 'add') {
        insertDept(props.ruleForm).then(res => {
          const code = res.code;
          const message: string = res.message;
          const data = res.data;
          if (code == 200) {
            ElMessage({
              message: '添加数据成功',
              type: 'success',
            })
            refushList.value = true
            closeEditDialog()
          }
        })
      } else if (props.addDataType === 'edit') {
        updateDept(props.ruleForm).then(res => {
          const code = res.code;
          const message: string = res.message;
          const data = res.data;
          if (code == 200) {
            ElMessage({
              message: '更新数据成功',
              type: 'success',
            })
            refushList.value = true
            closeEditDialog()
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const areaData = async (val: any) => {
  return await findAreaByParentCode(val);
}

const setProvinceData = async (val: any) => {
  const res = await areaData(val);
  const code = res.code
  const message = res.message
  const data = res.data as Array<Area>
  if (code == 200) {
    address.province = data
  }
}

const setCityData = async (val: any) => {
  const res = await areaData(val);
  const code = res.code
  const message = res.message
  const data = res.data as Array<Area>
  if (code == 200) {
    address.city = data
  }
}

const setDistrictData = async (val: any) => {
  const res = await areaData(val);
  const code = res.code
  const message = res.message
  const data = res.data as Array<Area>
  if (code == 200) {
    address.district = data
  }
}

const provinceChange = (val: any) => {
  props.ruleForm.province = val
  address.city = []
  address.district = []
  props.ruleForm.city = []
  props.ruleForm.district = []
  setCityData(val)
}

const cityChange = (val: any) => {
  props.ruleForm.city = val
  address.district = [];
  props.ruleForm.district = []
  setDistrictData(val)
}

onMounted(async () => {
  await setProvinceData(100000)
  if (!props.ruleForm.province) {
    props.ruleForm.province = address.province[0].code
  }
  if (props.ruleForm.province) {
    await setCityData(props.ruleForm.province)
  }

  if (!props.ruleForm.city) {
    props.ruleForm.city = address.city[0].code
  }
  if (props.ruleForm.city) {
    await setDistrictData(props.ruleForm.city)
  }

  if (address.district.length!=0){
    props.ruleForm.district = address.district[0].code
  }

  await deptLoop().then(res => {
    const code = res.code
    const message = res.message
    const data = res.data as Array<Dept>
    if (code == 200) {
      parentDepts.value = data;
    }
  })
})

</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

::v-deep .el-cascader__tags .el-cascader__search-input {
  min-width: 0;
}

.el-select {
  width: 100%;
}

.address-top {
  padding-top: 20px;
}
</style>
